package com.tl.sun.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.EmptyUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.callback.StringCallback;
import com.orhanobut.logger.Logger;
import com.tl.sun.AppConfig;
import com.tl.sun.AppContext;
import com.tl.sun.AppManager;
import com.tl.sun.OkHeader;
import com.tl.sun.R;
import com.tl.sun.api.network.StringDialogCallback;
import com.tl.sun.helper.UIHelper;
import com.tl.sun.manager.MDAccountMgr;
import com.tl.sun.manager.MDUserMgr;
import com.tl.sun.model.BaseModel;
import com.tl.sun.model.ExceedUserEnetity;
import com.tl.sun.model.RegistPhone;
import com.tl.sun.model.SessionEnetity;
import com.tl.sun.model.UserEnetity;
import com.tl.sun.utils.DeviceUuidFactory;
import com.tl.sun.utils.ToastUtil;
import com.tl.sun.utils.common.MD5Util;
import com.tl.sun.utils.common.RegularUtils;
import com.tl.sun.widgets.ButtonTimer;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by apple on 16/10/12.
 */

public class RegistActivity extends BaseActivity {

    @Bind(R.id.rl_generic_back)
    RelativeLayout mRlGenericBack;
    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.et_regist_pass)
    EditText mEtRegistPass;
    @Bind(R.id.iv_regist_check)
    ImageView mIvRegistCheck;
    @Bind(R.id.rl_regist_password)
    RelativeLayout mRlRegistPassword;
    @Bind(R.id.btn_login_submit)
    Button mBtnLoginSubmit;
    @Bind(R.id.checkbox)
    CheckBox mCheckBox;
    @Bind(R.id.tv_agreement)
    TextView mTvAgreement;
    private boolean isOn = true;
    private String time;

    @Bind(R.id.et_bind_phone)
    EditText mEtBindPhone;
    @Bind(R.id.et_bind_code)
    EditText mEtBindCode;
    @Bind(R.id.bt_bind_code)
    ButtonTimer mBtBindCode;
    @Bind(R.id.et_bind_verfiy)
    EditText mEtBindVerfiy;
    @Bind(R.id.iv_bind_verfiy)
    ImageView mIvBindVerfiy;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        ButterKnife.bind(this);
        init();
        getImgVerify();
    }

    public void init() {
        mTvGenericTitle.setText("注册");
        //阅读并同意⟪ZhiMa Proxy用户注册协议⟫

        String trim = mTvAgreement.getText().toString().trim();
        SpannableString spanString = new SpannableString(trim);
        UnderlineSpan span = new UnderlineSpan();
        spanString.setSpan(span, 6, trim.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvAgreement.setText(spanString);
    }


    public void getImgVerify() {
        OkGo.post(AppContext.getInstance().getBaseUrl() + "account/verify").tag("verify")
                .execute(new BitmapCallback() {
                    @Override
                    public void onSuccess(Bitmap bitmap, Call call, Response response) {
                        mIvBindVerfiy.setImageBitmap(bitmap);

                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //根据 Tag 取消请求
        OkGo.getInstance().cancelTag(this);
    }

    @OnClick({R.id.rl_generic_back, R.id.iv_bind_verfiy, R.id.btn_login_submit, R.id.rl_regist_password, R.id.tv_agreement, R.id.bt_bind_code})
    public void onClick(View view) {
        String phone = mEtBindPhone.getText().toString();
        String phoneCode = mEtBindCode.getText().toString();
        String password = mEtRegistPass.getText().toString();
        String verfiy = mEtBindVerfiy.getText().toString();
        switch (view.getId()) {
            case R.id.rl_generic_back:
                onBackPressed();
                break;
            case R.id.iv_bind_verfiy:
                getImgVerify();
                break;
            case R.id.bt_bind_code:
                if (TextUtils.isEmpty(phone)) {
                    ToastUtil.showToast(getString(R.string.et_is_phone_empty));
                } else {
                    if (RegularUtils.isMobileExact(phone)) {
                        if (EmptyUtils.isNotEmpty(verfiy)) {
                            getCode(phone, verfiy);
                        } else {
                            ToastUtil.showToast(getString(R.string.et_is_verify_empty));
                        }
                    } else {
                        ToastUtil.showToast("手机号格式不正确!");
                    }
                }
                break;
            case R.id.btn_login_submit:
                if (!TextUtils.isEmpty(phone)) {
                    if (!TextUtils.isEmpty(password)) {
                        if (!RegularUtils.isUsername2(phone)) {
                            ToastUtil.showToast("手机号格式不正确!");
                        } else {
                            if (password.length() >= 6 && password.length() <= 30) {
                                if (mCheckBox.isChecked()) {
                                    setRegist(password, verfiy, phone, phoneCode);
                                } else {
                                    ToastUtil.showToast("请阅读并同意《太阳代理用户协议》");
                                }
                            } else {
                                ToastUtil.showToast(getResources().getString(R.string.et_length));
                            }
                        }
                    } else {
                        ToastUtil.showToast(getResources().getString(R.string.et_is_password_empty));
                    }
                } else {
                    ToastUtil.showToast(getResources().getString(R.string.et_is_phone_empty));
                }

                break;
            case R.id.rl_regist_password:
                if (isOn) {
                    isOn = false;
                    mIvRegistCheck.setSelected(false);
                    mEtRegistPass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    isOn = true;
                    mIvRegistCheck.setSelected(true);
                    mEtRegistPass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                mEtRegistPass.postInvalidate();
                break;
            case R.id.tv_agreement:
                UIHelper.goWebViewIntent(this, "太阳代理用户注册协议 ", AppConfig.getInstance().getAppInfo().getAgreementUrl());
                break;
                default:
                    break;
        }
    }


    public void getCode(String phone, String verfiy) {
        HashMap<String, String> map = new HashMap<>();
        map.put("num", phone);
        map.put("code", "rst_pass");
        map.put("verify", verfiy);
        JSONObject json = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(this)).post(AppContext.getInstance().getBaseUrl() + "account/get_code_new")
                .tag(RegistActivity.this)
                .upJson(json.toString())
                .execute(new StringDialogCallback(RegistActivity.this, "加载中...", true) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        if (baseModel.getRet().equals("0")) {
                            mBtBindCode.setTimes(60);
                            mBtBindCode.setType("1");
                            if (!mBtBindCode.isRun()) {
                                mBtBindCode.beginRun();
                                mBtBindCode.setEnabled(false);
                            }
                            ToastUtil.showToast(baseModel.getMsg());
                        } else {
                            getImgVerify();
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }
                });

    }

    public void setRegist(final String pass, String code, final String phone, String phonecode) {
        HashMap<String, String> map = new HashMap<>();
        map.put("password", pass);
        map.put("re_password", pass);
        map.put("verify", code);
        map.put("verify_id", time);
        map.put("promoter", "");
        map.put("version", AppContext.version);
        map.put("platform", "android");
        map.put("client_id", MD5Util.md5(new DeviceUuidFactory(AppContext.getInstance()).getDeviceUuid().toString()));
        map.put("phone", phone);
        map.put("phone_code", phonecode);
        JSONObject jsonObject = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(this)).post(AppContext.getInstance().getBaseUrl() + "account/reg_new_v1_v2")
                .tag(this)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Logger.e("注册返回: " + s);

                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        if (baseModel.getRet().equals("0")) {

                            Type registType = new TypeToken<BaseModel<RegistPhone>>() {
                            }.getType();
                            BaseModel<RegistPhone> phoneBase;
                            try {
                                phoneBase = gson.fromJson(s, registType);

                            } catch (Exception e) {
                                phoneBase = gson.fromJson(s, BaseModel.class);
                            }
                            String type = null;
                            if (EmptyUtils.isNotEmpty(phoneBase.getData().getIsBind())) {
                                if (phoneBase.getData().getIsBind() == 1) {
                                    type = "1";
                                } else {
                                    type = "0";
                                }
                            } else {
                                type = "0";
                            }
                            login(phone, pass);
                            finish();
                        } else {
                            getImgVerify();
                            ToastUtil.showToast(baseModel.getMsg());
                        }

                    }
                });
    }

    /**
     * 登录
     *
     * @param name
     * @param password
     */
    public void login(final String name, final String password) {
        HashMap<String, String> map = new HashMap<>();
        map.put("username", name);
        map.put("password", password);
        map.put("client_id", MD5Util.md5(new DeviceUuidFactory(AppContext.getInstance()).getDeviceUuid().toString()));
        map.put("device_token", MDAccountMgr.getInstance().getDeviceToken());
        JSONObject jsonObject = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(this)).post(AppContext.getInstance().getBaseUrl() + "account/login_v2")
                .tag(this)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModels = gson.fromJson(s, BaseModel.class);
                        if (baseModels.getRet().equals("0")) {
                            Type userType = new TypeToken<BaseModel<SessionEnetity>>() {
                            }.getType();
                            BaseModel<SessionEnetity> baseModel;
                            try {
                                baseModel = gson.fromJson(s, userType);
                            } catch (JsonSyntaxException e) {
                                baseModel = gson.fromJson(s, BaseModel.class);
                            }
                            SessionEnetity sessionInfo = baseModel.getData();
                            MDAccountMgr.getInstance().setSessionId(sessionInfo.getSession());
                            UserEnetity user = sessionInfo.getUserInfo();
                            MDUserMgr.getInstance().setAvatar(user.getAvatar());
                            MDUserMgr.getInstance().setAwardFlag(user.getAward_flag());
                            MDUserMgr.getInstance().setId(user.getId());
                            MDUserMgr.getInstance().setUsername(user.getUsername());
                            MDUserMgr.getInstance().setShowName(user.getShowNmae());
                            MDUserMgr.getInstance().setNickname(user.getNick_name());
                            MDUserMgr.getInstance().setChange(user.getChange());
                            MDUserMgr.getInstance().setEmail(user.getEmail());
                            MDUserMgr.getInstance().setPhone(user.getPhone());
                            MDUserMgr.getInstance().setMoney(Double.valueOf(user.getMoney()));
                            MDUserMgr.getInstance().setLastTime(user.getLast_time());
                            MDUserMgr.getInstance().setLastTimeType(user.getLast_time_type());
                            MDUserMgr.getInstance().setStatus(user.getStatus());
                            MDUserMgr.getInstance().setToken(user.getToken());
                            MDUserMgr.getInstance().setTime(user.getnVipTime() );
                            MDUserMgr.getInstance().setsTime(user.getsVipTime() );
                            MDUserMgr.getInstance().setCoupoum(user.getCoupoum());
                            MDUserMgr.getInstance().setLogin(true);//保存到类

                            MDUserMgr.getInstance().setThreeDayExpire(user.getThreeDayExpire());
                            MDAccountMgr.getInstance().setLogin(true);//保存到内存
                            MDAccountMgr.getInstance().setLoginName(user.getShowNmae());
                            MDAccountMgr.getInstance().setLoginPwd(password);

                            MDAccountMgr.getInstance().setPassowrd(true);
                            MDAccountMgr.getInstance().writeToCache(RegistActivity.this);
                            AppManager.getAppManager().finishActivity(LoginActivity.class);

                            Intent login = new Intent(RegistActivity.this, MainActivity.class);
                            startActivity(login);
                            finish();
                        } else if (baseModels.getRet().equals("1")) {
                            Type exceed = new TypeToken<BaseModel<List<ExceedUserEnetity>>>() {
                            }.getType();
                            BaseModel<List<ExceedUserEnetity>> exceeModel;
                            try {
                                exceeModel = gson.fromJson(s, exceed);
                            } catch (JsonSyntaxException e) {
                                exceeModel = gson.fromJson(s, BaseModel.class);
                            }
                            if (exceeModel.getCode().equals("overtop")) {
                                UIHelper.showTerminal(RegistActivity.this, exceeModel.getData(), UIHelper.LOGIN_DIALOG, "2");
                            } else {
                                ToastUtil.showToast(baseModels.getMsg());
                            }
                        } else {
                            ToastUtil.showToast(baseModels.getMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        ToastUtil.showToast("网络请求失败");
                    }

                });
    }
}
